package toolbox

import (
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/interface/runner"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/goroutine"
	"time"
)

func NewDownloader() runner.Runner {
	return func(ctx context.Context) (<-chan struct{}, error) {
		var ch = make(chan struct{}, 1)

		var downloader = GetDownloader()
		goroutine.Go(func() {
			var ticker = time.NewTicker(time.Hour)
			defer ticker.Stop()

			for {
				select {
				case <-ctx.Done():
					downloader.CancelAll()
					downloader.WaitCancel()

					logger.GetLogger().Sugar().Info("下载器已退出")
					ch <- struct{}{}

					return
				case <-ticker.C:
					downloader.Clean(nil)
				}
			}
		})

		return ch, nil
	}
}
